<!DOCTYPE html>

<html lang="en-us"><head>
  <meta charset="utf-8">
  <title>文章详情</title>
  <script src="js/vue.js"></script>
  <script src="./js/axios.js"></script>

  <!-- mobile responsive meta -->
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="This is meta description">
  <meta name="generator" content="Hugo 0.74.3" />

  <!-- plugins -->
  
  <link rel="stylesheet" href="plugins/bootstrap/bootstrap.min.css">
  <link rel="stylesheet" href="plugins/themify-icons/themify-icons.css">
  <link rel="stylesheet" href="plugins/slick/slick.css">

  <!-- Main Stylesheet -->
  <link rel="stylesheet" href="css/style.css" media="screen">

  <!--Favicon-->
  <link rel="shortcut icon" href="images/favicon.png" type="image/x-icon">
  <link rel="icon" href="images/favicon.png" type="image/x-icon">

  <meta property="og:title" content="Reader | Hugo Personal Blog Template" />
  <meta property="og:description" content="This is meta description" />
  <meta property="og:type" content="website" />
  <meta property="og:url" content="" />
  <meta property="og:updated_time" content="2020-03-15T15:40:24+06:00" />
</head>
<body>
 <!-- navigation -->
  <!-- navigation -->
 <!-- navigation -->
 <header class="navigation">
    <div class="container" id="index">
      <nav class="navbar navbar-expand-lg navbar-white">
        <a class="navbar-brand order-1" href="index.html">
          <img class="img-fluid" width="50px" src="images/图标.png"
            alt="中国传统文化论坛">
        </a>
        <div class="collapse navbar-collapse text-center order-lg-2 order-3" id="navigation">
          <ul class="navbar-nav mx-auto">
            <li class="nav-item active">
              <a class="nav-link" href="index.html">首页</a>
            </li>
            <li class="nav-item @@about__active">
              <a class="nav-link" href="BBS_index.html">论坛</a>
            </li>
            <li class="nav-item @@services__active">
              <a class="nav-link" href="chat.html">消息</a>
            </li>
            <li class="nav-item @@services__active">
              <a class="nav-link" href="shop.html">商店</a>
            </li>
          </ul>
        </div>
        <div class="order-2 order-lg-3 d-flex align-items-center">
          <form @submit.prevent="performSearch"> <!-- 阻止表单提交 -->
            <input 
              id="search-query" 
              name="s" 
              type="search" 
              placeholder="输入文章ID"
              v-model="searchId" 
            >
            <button type="submit" class="btn btn-search">搜索</button>
          </form>
          <button class="navbar-toggler border-0 order-1" type="button" data-toggle="collapse" data-target="#navigation">
            <i class="ti-menu"></i>
          </button>
          <ul class="navbar-nav ml-auto" v-if="userid==null">
            <li class="nav-item @@login__active">
                <a class="nav-link" href="Login.html">登录</a>
            </li>
            <li class="nav-item @@register__active">
                <a class="nav-link" href="register.html">注册</a>
            </li>
        </ul>
        <ul class="navbar-nav ml-auto 1ogined" v-else>
            <li class="nav-item @@login__active">
              <span><a class="nav-link" href="person-post.html">{{userid}}</a></span>
            </li>
            <li class="nav-item @@register__active">
                <span v-on:click.prevent="logout"><a class="nav-link" href="BBS_index.html">注销</a></span>
            </li>
        </ul>
        </div>
      </nav>
    </div>
  </header>
  
  
    <!--引导程序-->
    <script src="js/jquery-3.3.1.min.js"></script> 
    <script src="js/bootstrap.min.js"></script>
    <!--/MENU-JS-->
    <script>
        new Vue({
          el: "#index",
          data: {
            userid: localStorage["userid"],
            searchId: '' // 用于存储搜索的ID
          },
          methods: {
            logout: function() {
              localStorage.clear();
              this.userid = null;
            },
            performSearch: function() {
              if (!this.searchId || this.searchId.trim() === '') {
                // 如果为空，跳转到404页面
                alert("请输入文章id");
                return;
              }
              // 存储搜索ID到localStorage
              localStorage.setItem("num", this.searchId);
              // 跳转到post.html
              location.href = "post.html";
            }
          }
        })
    </script>
<!-- /navigation -->
<section class="section">
  <div class="container" id="newpost">
    <div class="row justify-content-center">
      <div class=" col-lg-9 mb-5 mb-lg-0">
        <article>
          <h1 class="h2">{{post.title}}</h1>
          <ul class="card-meta my-3 list-inline">
            <li class="list-inline-item">
              <a class="card-meta-author">
                <span>{{post.userId}}</span>
              </a>
            </li>
            <li class="list-inline-item">
              <i class="ti-calendar"></i>{{ post.time.replace('T', ' ') }}
            </li>
            <li class="list-inline-item">
              <ul class="card-meta-tag list-inline">
                <li class="list-inline-item"><a @click="storetag(post.topicType)">{{post.topicType}}</a></li>
              </ul>
            </li>
          </ul>
          <div class="content" v-html="formattedText">
            {{post.text}}
          </div>
        </article>
        
      </div>
      <div class="col-lg-9 col-md-12r">
        <div class="like-section mt-4">
          <button @click="toggleLike" class="btn" :class="{'btn-danger': isLiked, 'btn-outline-danger': !isLiked}">
              <i class="bi" :class="{'bi-heart-fill': isLiked, 'bi-heart': !isLiked}"></i>
              {{isLiked ? '取消点赞' : '点赞'}}
          </button>
          <span id="like-count" class="ms-2">{{post.likeNum}} Likes</span>
      </div>
    </div>
      
      <div class="col-lg-9 col-md-12" >
          <div class="mb-5 border-top mt-4 pt-5">
            <div v-if="String(userid) !== String(post.userId)" class="form-group col-md-12">
              <textarea class="form-control shadow-none" name="comment" v-model="newMessage" rows="7" required></textarea>
           </div>
            <button v-if="String(userid) !== String(post.userId)"  @click="sendPrivateMessage(post.userId)" class="btn btn-primary ms-2">
              <i class="bi bi-envelope"></i>
              发送私信
            </button>
            <div v-if="String(userid) !== String(post.userId)" class="mb-4 border-top mt-4 pt-4"></div>
              <h3 class="mb-4">评论区</h3>
              <div v-for="(item, index) in comments" :key="item" class="media d-block d-sm-flex mb-4 pb-4">
                  <a class="d-inline-block mr-2 mb-3 mb-md-0" href="#">
                  </a>
                  <div class="media-body">
                    <a class="h4 d-inline-block mb-3">{{ item.ownerId }}</a>
                    <p>{{ item.text }}</p>
                  <span class="text-black-800 mr-3 font-weight-600">{{ item.time.replace('T', ' ') }}</span>
                  </div>
              </div>
          </div>

          <div>
            <h3 class="mb-4">留下评论</h3>
            <form method="POST">
                <div class="row">
                    <div class="form-group col-md-12">
                        <textarea class="form-control shadow-none" name="comment" v-model="text" rows="7" required></textarea>
                    </div>
                </div>
                <button class="btn btn-primary" type="submit" v-on:click.prevent="addComments"> 评论</button>
            </form>
        </div>
    </div>
      
    </div>
  </div>
</section>

<script>
    var vm = new Vue({
      el: "#newpost",
      data: {
        userid: localStorage["userid"],
        comments: [],
        post: JSON.parse(window.localStorage.getItem("postInfo" + localStorage["num"])),
        isLiked: false,
      },
      computed: {
          formattedText() {
            // 将换行符转换为<p>标签，并且每个段落都缩进
            return this.post.text
              .split('\n')   // 根据换行符分割文本
              .map(paragraph => `<p class="artic">${paragraph}</p>`)  // 每一段包装为<p>标签
              .join('');     // 合并所有段落
          }
        },
      mounted() {
        // 从 localStorage 中获取点赞状态
        const likedPosts = JSON.parse(localStorage.getItem('likedPosts') || '{}');
        this.isLiked = likedPosts[this.post.id] || false;
        this.fetchLatestPostInfo();
        this.fetchComments();
      },
      methods: {
        addComments() {
          const newComment = {
            ownerId: localStorage.getItem('userid'),
            text: this.text,
            postId: this.post.id
          };
          axios.post("https://localhost:7071/api/Comment", newComment)
          .then((res) => {
            console.log(res);
            // 判断响应值是否为 -1
            if (res.data === -1) {
              // 弹窗提示用户被禁言
              alert("您被禁言，无法评论");
              this.text = ''; // 清空评论输入框
            } else {
              // 如果返回的不是 -1，继续执行正常的逻辑
              this.fetchComments(); // 调用 fetchComments 方法
              this.text = ''; // 清空评论输入框
            }
          })
          .catch(error => {
            console.error('添加评论失败:', error);
          });
        },
        async sendPrivateMessage(ownerId) {
          try {
            var userid = localStorage["userid"];
              var message = {
                messageId: 0,
                senderId: userid, // 当前用户的 ID
                receiverId: ownerId, // 选择的用户的 ID
                text: this.newMessage, // 输入框中的消息内容
                timestamp: new Date().toISOString(), // 获取当前时间戳（ISO 格式）
                isRead: false, // 默认消息未读
              };
              if(message){
                // 发送 POST 请求到后端
                const response = await axios.post('https://localhost:7071/api/Message', message);
                if (response.data!=null) {
                  this.newMessage = '';
                  console.log('Message sent successfully');
                  alert("消息发送成功");
                  window.location.href = "chat.html";
                  }
              }
          } catch (error) {
            console.error('Error sending private message:', error);
          }
        },

        fetchComments() {
                  const postId = this.post.id;
                  axios.get('https://localhost:7071/api/Comment?id=-1&ownerId=-1&postId=' + postId)
                  .then((res) =>
                        {
                          // 清空原有的评论列表
                          this.comments = [];
                          res.data.sort((a, b) => new Date(b.time) - new Date(a.time));
                            for(d in res.data){
                                this.comments.push(res.data[d]);
                            }
                        })
              },

        fetchLatestPostInfo() {
          const postId = this.post.id;
          axios.get(`https://localhost:7071/api/Post/${postId}`)
            .then(response => {
              // 更新文章信息，但保持其他本地状态不变
              const updatedPost = {
                ...this.post,
                likeNum: response.data.likeNum
              };
              this.post = updatedPost;

              // 更新 localStorage 中的文章信息
              localStorage.setItem("postInfo" + localStorage["num"], JSON.stringify(updatedPost));
            })
            .catch(error => {
              console.error('获取文章信息失败:', error);
            });
        },

        toggleLike: function() {
          const postId = this.post.id;
          const url = this.isLiked
            ? `https://localhost:7071/api/Post/dislike?postId=${postId}`
            : `https://localhost:7071/api/Post/like?postId=${postId}`;
          axios.post(url)
            .then(response => {
              // 切换点赞状态
              this.isLiked = !this.isLiked;

              // 更新点赞数
              if (this.isLiked) {
                this.post.likeNum++;
              } else {
                this.post.likeNum--;
              }

              // 保存点赞状态到 localStorage
              const likedPosts = JSON.parse(localStorage.getItem('likedPosts') || '{}');
              likedPosts[postId] = this.isLiked;
              localStorage.setItem('likedPosts', JSON.stringify(likedPosts));

              // 更新 localStorage 中的文章信息
              localStorage.setItem("postInfo" + localStorage["num"], JSON.stringify(this.post));
            })
            .catch(error => {
              console.error('点赞操作失败:', error);
            });
        },
        storetag: function(topicType) {
          localStorage.setItem("selectedTag", topicType);
          location.href = "tags.html";
        }
      }
    });
</script>

<footer class="footer">
  <svg class="footer-border" height="214" viewBox="0 0 2204 214" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M2203 213C2136.58 157.994 1942.77 -33.1996 1633.1 53.0486C1414.13 114.038 1200.92 188.208 967.765 118.127C820.12 73.7483 263.977 -143.754 0.999958 158.899"
      stroke-width="2" />
  </svg>
  <div class="container">
      <div class="row align-items-center">
      <div class="col-md-5 text-center text-md-left mb-4">
          <ul class="list-inline footer-list mb-0">
            <li class="list-inline-item"><a href="privacy-policy.html">Privacy Policy</a></li>
          </ul>
      </div>
      <div class="col-md-2 text-center mb-4">
          <a href="index.html"><img class="img-fluid" width="100px" src="images/图标.png" alt="Reader | Hugo Personal Blog Template"></a>
      </div>
      <div class="col-12">
          <div class="border-bottom border-default"></div>
      </div>
      </div>
  </div>
  </footer>


  <!-- JS Plugins -->
  <script src="plugins/jQuery/jquery.min.js"></script>

  <script src="plugins/bootstrap/bootstrap.js"></script>

  <script src="plugins/slick/slick.min.js"></script>

  <script src="plugins/instafeed/instafeed.min.js"></script>


  <!-- Main Script -->
  <script src="js/script.js"></script></body>
</html>